﻿using EasyAdmin.DatabaseAccessor.SqlSugar.Attributes;
using EasyCore.Reflection;
using Microsoft.AspNetCore.Connections.Features;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace EasyAdmin.DatabaseAccessor.SqlSugar.Extensions
{
    /// <summary>
    /// SqlSugarClient扩展类
    /// </summary>
    public static class SqlSugarClientExtensions
    {
        /// <summary>
        /// 初始化数据库
        /// </summary>
        /// <param name="client"></param>
        public static void InitDatabase(this ISqlSugarClient client)
        {

        }

        /// <summary>
        /// 初始化所有表
        /// </summary>
        /// <param name="client"></param>
        public static void InitTables(this ISqlSugarClient sqlSugarClient)
        {
            if (sqlSugarClient == null) return;
            var client = sqlSugarClient as SqlSugarClient;
            var configIds = client.GetCurrentConfigIds();
            if (configIds == null || !configIds.Any()) return;
            var entityTypes = AssemblyManager.FindTypes(m => m.IsClass && !m.IsInterface && !m.IsAbstract && m.IsDefined(typeof(SugarTable), false));
            if (entityTypes == null || !entityTypes.Any()) return;//获得所有实体类型

            //多租户多库支持
            Dictionary<string, SqlSugarScopeProvider> providers = new Dictionary<string, SqlSugarScopeProvider>();
            Func<string, SqlSugarScopeProvider> getSqlSugarScopeProvider = (configId) =>
            {
                if (providers.ContainsKey(configId))
                    return providers[configId];
                var sqlSugarScopeProvider = client.GetConnectionScope(configId);
                if (sqlSugarScopeProvider != null) {
                    providers.Add(configId, sqlSugarScopeProvider);
                    return sqlSugarScopeProvider;
                }
                return null;     
            };

            //实体拓展配置,自定义类型多库兼容
            foreach (var entityType in entityTypes)
            {
                var ignoreInit = entityType.GetCustomAttribute<IgnoreInitTableAttribute>();//获取忽略初始化特性
                if (ignoreInit != null) continue;//如果有忽略初始化特性
                var tenantAtt = entityType.GetCustomAttribute<TenantAttribute>();//获取Sqlsugar多租户特性
                //如果特性存在并且租户ID不是当前数据库ID
                var configId = tenantAtt == null || tenantAtt.configId == null || string.IsNullOrWhiteSpace((string)tenantAtt.configId) ? SqlSugarConst.DEFAULT_DB_CONFIG_ID : tenantAtt.configId.ToString();
                var provider = getSqlSugarScopeProvider(configId);
                if (provider == null) continue;
                var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();//获取自动分表特性
                if (splitTable == null)//如果特性是空
                    provider.CodeFirst.InitTables(entityType);//普通创建
                else
                    provider.CodeFirst.SplitTables().InitTables(entityType);//自动分表创建
            }   
        }

    }
}
